package com.yunshang.ysmall.controller;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.apache.http.client.HttpClient;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import ch.qos.logback.core.net.LoginAuthenticator;

import com.alibaba.fastjson.JSONObject;
import com.richerpay.utils.HttpClientUtils;
import com.richerpay.utils.HttpRequest;
import com.richerpay.utils.SignatureUtil;
import com.yunshang.ysmall.model.CodePayModel;
import com.yunshang.ysmall.util.DateUtils;
@Controller
@RequestMapping("/qianfang")
public class QianFangController {
	/*private static final String QF_KEY="7AB7F12D1A374208BA9A9E29E337BAEE";//钱方的key
	private static final String QF_CODE="1FC313D7DF494B9E8CE9A6C28C190EBB";//钱方的code
*/	
	private static String REQUEST_URL = "https://openapi.qfpay.com";

	private static String QF_KEY = "A59FC941F3DB46F3B20379C924B4FB25";

	private static String QF_CODE = "FAEF5D1CA0D54BDBA972298A222E1476";
	
	Logger logger=LoggerFactory.getLogger(QianFangController.class);
	
	//获取钱方的code是011zMkEQ0mEe5822zjEQ0K9zEQ0zMkEp
	@Test
	public void test1(){
		String redirect_uri="http://www.houheshangpin.com/weChat/weChatTest";//回调地址
		Map<String, String> map = new HashMap<String, String>();
		map.put("app_code",QF_CODE);
		map.put("redirect_uri",redirect_uri);
		String md5Str = SignatureUtil.createLinkString(map)+QF_KEY;
		//设置签名
		String sign = SignatureUtil.md5Encrypt(md5Str);
		
		try {
			String result1=HttpClientUtils.httpGet(REQUEST_URL+"/tool/v1/get_weixin_oauth_code?app_code="+QF_CODE+
			"&redirect_uri="+redirect_uri+"&sign="+sign);
			System.out.println(REQUEST_URL+"/tool/v1/get_weixin_oauth_code?app_code="+QF_CODE+
					"&redirect_uri="+redirect_uri+"&sign="+sign);
			logger.info("["+Thread.currentThread().getId()+"]"+"[qiangfang code]"+result1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	//获取openId   oppenid=oo3Lss5Yr3vmpoPo8ZZsGQlGFFAI
	
//	{"resperr": "", "respcd": "0000", "respmsg": "", "openid": "oo3Lss5Yr3vmpoPo8ZZsGQlGFFAI"}
	@Test
	public void test2(){
		String code="0011S3Xf2fh4OB0MuNXf28jcXf21S3Xf";
		Map<String, String> map = new HashMap<String, String>();
		map.put("code",code);
		String md5Str = SignatureUtil.createLinkString(map)+QF_KEY;
		//设置签名
		String sign = SignatureUtil.md5Encrypt(md5Str);
		
		try {
		//返回响应的参数
			String result1=HttpClientUtils.httpGetForQf(REQUEST_URL+"/tool/v1/get_weixin_openid?code="+code,QF_CODE,sign);
//			System.out.println("https://openapi-test.qfpay.com/tool/v1/get_weixin_openid?code="+code);
			System.out.println(result1);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//
	
	
	//调用请求支付接口
	public void test3(){
		CodePayModel codePayModel=new CodePayModel();
		codePayModel.setGoodsName("厚合正式支付商品");
		String date=DateUtils.currentDate("yyyy-MM-dd HH:mm:ss");
		String orderId=date+"houhe"+UUID.randomUUID();
		System.out.println(orderId);
		codePayModel.setMerchantOrderId(orderId);
		codePayModel.setTradeAmount(new BigDecimal(1));
		codePayModel.setOpenId("oo3Lss5Yr3vmpoPo8ZZsGQlGFFAI");
		CodePayModel codePayModel1;
		try {
			codePayModel1 = this.unifiedOrder(codePayModel);
			System.out.println(codePayModel1);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	/*
	"package": "prepay_id=wx20171115180147c61b543bb90067744283", 
	"timeStamp": "1510740107301", "signType": "MD5", 
	"paySign": "5801B1445486C2DF82EE51288CC8D586",
	 "appId": "wx290ce4878c94369d", "nonceStr": "1510740107301"}
	*/
	
	//跳转到支付页面
public void test4(){
		Map<String ,String> map=new HashMap<String ,String>();
		map.put("mchntnm","邦呈");//
		map.put("txamt","100");
		map.put("goods_name", "厚合微信支付");
		map.put("redirect_url","http://www.houheshangpin.com/weChat/weChatPay");
		map.put("package","prepay_id=wx20171115180147c61b543bb90067744283");
		map.put("timeStamp","1510740107301");
		map.put("signType","MD5");
		map.put("paySign","5801B1445486C2DF82EE51288CC8D586");
		map.put("appId","wx290ce4878c94369d");
		map.put("nonceStr","1510740107301");
		String md5Str = SignatureUtil.createLinkString(map)+QF_KEY;
		//设置签名
		String sign = SignatureUtil.md5Encrypt(md5Str);
		try {
		/*System.out.println("https://o2.qfpay.com/q/direct?mchntnm="+map.get("mchntnm")+"&txamt="+map.get("txamt")
			+"&goods_name="+map.get("goods_name")+"&redirect_url="+map.get("redirect_url")+"&package="+map.get("package")+"&timeStamp"+map.get("timeStamp")
			+"&signType="+map.get("signType")+"&appId="+map.get("appId")+"&nonceStr="+map.get("nonceStr"));*/
		String  ssString="https://o2.qfpay.com/q/direct?mchntnm="+URLEncoder.encode("邦呈","utf-8")+"&txamt=100&goods_name="+URLEncoder.encode("厚合微信支付","utf-8")+
				"&redirect_url=http://www.houheshangpin.com/weChat/weChatPay&package="+map.get("package")+"&timeStamp="+map.get("timeStamp")+"&signType=MD5&appId="+map.get("appId")+"&nonceStr="+map.get("nonceStr")+"&paySign="+map.get("paySign");
//			System.out.println(URLEncoder.encode("邦呈","utf-8")+"--------------------------------------------");
		System.out.println(ssString);
			String resultString=HttpClientUtils.httpGetForQf("https://o2.qfpay.com/q/direct&mchntnm="+map.get("mchntnm")+"&txamt="+map.get("txamt")
			+"&goods_name="+map.get("goods_name")+"&redirect_url="+map.get("redirect_url")+"&package="+map.get("package")+"&timeStamp"+map.get("timeStamp")
			+"&signType="+map.get("signType")+"&appId="+map.get("appId")+"&nonceStr="+map.get("nonceStr"), QF_CODE, sign);
//			System.out.println(resultString);
		} catch (Exception e) {
			e.printStackTrace();
			
		}
//		String ssString="https://o2.qfpay.com/q/direct?app_code=1FC313D7DF494B9E8CE9A6C28C190EBB&redirect_uri=http://www.houheshangpin.com/weChat/weChatPay&sign=95BF5DB9F79F311CEA23681F209158DD";
}
	
	
/*	//	获取微信oauth的code
	@ResponseBody
	@RequestMapping("/weixinCode")
	public  String weixinCode(){
		String redirect_uri="http://test.qfpay.com";//回调地址
		Map<String, String> map = new HashMap<String, String>();
		map.put("app_code",QF_CODE);
		map.put("redirect_uri",redirect_uri);
		String md5Str = SignatureUtil.createLinkString(map)+QF_KEY;
		//设置签名
		String sign = SignatureUtil.md5Encrypt(md5Str);
		
		try {
			String result1=HttpClientUtils.httpGet("https://openapi-test.qfpay.com/tool/v1/get_weixin_oauth_code?app_code="+QF_CODE+
			"&redirect_uri="+redirect_uri+"&sign="+sign);
			System.out.println("https://openapi-test.qfpay.com/tool/v1/get_weixin_oauth_code?app_code="+QF_CODE+
					"&redirect_uri="+redirect_uri+"&sign="+sign);
			
			
			String result = HttpClientUtils.httpPostForQfpay("https://openapi-test.qfpay.com/trade/v1/payment", map, QF_CODE, sign);
			System.out.println(result);
			logger.info("["+Thread.currentThread().getId()+"]"+"[qiangfang code]"+result1);
			System.out.println("[qiangfang code]"+result1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	@ResponseBody
	@RequestMapping("/weixin")
	public String  weixinPay(){
		CodePayModel codePayModel=new CodePayModel();
		try {
		codePayModel.setGoodsName("厚合支付商品");
		String date=DateUtils.currentDate("yyyy-MM-dd HH:mm:ss");
		String orderId=date+"houhe"+UUID.randomUUID();
		System.out.println();
		codePayModel.setMerchantOrderId(orderId);
//		codePayModel.setOpenId("o0L-G0RWmI64xmC5T_a2hSEOhVTM");
		codePayModel.setTradeAmount(new BigDecimal(1));
		CodePayModel codePayModel1=unifiedOrder(codePayModel);
		System.out.println(codePayModel1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/templates/mall/pay";
	}*/

	
	public CodePayModel unifiedOrder(CodePayModel codePayModel)
			throws Exception {
		
		Map<String, String> map = new HashMap<String, String>();

		map.put("txdtm",DateUtils.currentDate("yyyy-MM-dd HH:mm:ss"));//请求的交易时间
		map.put("goods_name", codePayModel.getGoodsName());//商品的名称和标示
		map.put("out_trade_no", codePayModel.getMerchantOrderId());//订单id
		map.put("mchid", "dWamPhlnpW");//子商户号
		map.put("pay_type", "800207");//微信公众号支付
		map.put("sub_openid", codePayModel.getOpenId());//微信公众号的id

		map.put("txcurrcd","CNY");//设置请求的币种
		map.put("txamt", codePayModel.getTradeAmount().movePointRight(2)
				.toString()); // 单位分
			//将参数进行加密
		String md5Str = SignatureUtil.createLinkString(map)+QF_KEY;
		//设置签名
		String sign = SignatureUtil.md5Encrypt(md5Str);
		//返回该线程的标识符
		logger.info("[" + Thread.currentThread().getId()
				+ "][send to qianfang]:" + JSONObject.toJSONString(map));
		//发送请求到钱方  REQUEST_URL+"/trade/v1/payment" 。第一个参数是发送的地址。第二个参数是传入的参数 。第三个是钱方的code 。第四个是钱方参数的签名
		String result = HttpClientUtils.httpPostForQfpay(REQUEST_URL+"/trade/v1/payment", map, QF_CODE, sign);
		System.out.println(result+"---------------------------");

		logger.info("[" + Thread.currentThread().getId()
				+ "][recv from qianfang]:" + result);
		JSONObject jsonObject = JSONObject.parseObject(result);
		logger.info("[pay_params]"+jsonObject.getJSONObject("pay_params")+"..................."+jsonObject.getJSONObject("pay_params").getString("appId"));
		if ("0000".equals(jsonObject.getString("respcd"))) {
			codePayModel.setResponseCode("0000");
			codePayModel.setCodePayOrderId(jsonObject.getString("syssn"));//钱方的订单号
		} else {
			//如果交易不成功则设置打印返回的交易码
			codePayModel.setResponseCode(jsonObject.getString("respcd"));
			//返回调式信息
			codePayModel.setResponseDesc(jsonObject.getString("respmsg"));
		}
		return codePayModel;
	}
}
